#include "server.h"

vector<bool> server::sock_addr(10000,false);//这里一定记得写server得作用域！！！不然编译器认为定义了一个新的sock_addr
server::server(int port,string ip):server_port(port),server_ip(ip) {}
server::~server()
{
    for(int i=0;i<sock_addr.size();++i)
        if(sock_addr[i])
            close(i);
    close(server_sockfd);
}

int ctoint(char *a)
{
    int sum=0;
    for(int i=strlen(a)-1;i>=0;--i)
        sum=sum*10+a[i]-'0';
    return sum+1;
}

string inttos(int a)
{
    if(a==0)
    {
        string res="0";
        return res;
    }
    string res;
    while(a>0)
    {
        res.push_back(a%10+'0');
        a/=10;
    }
    reverse(res.begin(),res.end());
    return res;
}

//记账
void record(MYSQL *con,string &str,string name)
{
    cout<<name<<endl;
    int pos_t=str.find("time:");
    int pos_w=str.find("way:");
    int pos_p=str.find("pay:");
    int pos_pl=str.find("place:");
    int pos_a=str.find("aim:");
    string time=str.substr(pos_t+5,pos_w-11);
    string way=str.substr(pos_w+4,pos_p-pos_w-4);
    string pay=str.substr(pos_p+4,pos_pl-pos_p-4);
    string place=str.substr(pos_pl+6,pos_a-pos_pl-6);
    string aim=str.substr(pos_a+4);

    string sqlstr="insert into cost values(";
    mysql_query(con,"select max(id)  from cost");
    auto result=mysql_store_result(con);
    auto ans=mysql_fetch_row(result);
    int col=mysql_num_fields(result);
    int row=mysql_num_rows(result);
    int len=ctoint(ans[0]);
    cout<<col<<" "<<row<<" "<<len<<endl;
    sqlstr+=inttos(len);
    sqlstr+=",\""+time+"\"";
    sqlstr+=",\""+way+"\"";
    sqlstr+=","+pay;
    sqlstr+=",\""+aim+"\"";
    sqlstr+=",\""+name+"\");";
    cout<<sqlstr<<endl;
    mysql_query(con,sqlstr.c_str());
    cout<<"添加成功!"<<endl;
}

void monthturn(string &str)
{
    // cout<<str<<endl;
    // if(str=="Jul\0") cout<<"YES"<<endl;
    if(str=="Jan") str="01";
    else if(str=="Feb") str="02";
    else if(str=="Mar") str="03";
    else if(str=="Apr") str="04";
    else if(str=="May") str="05";
    else if(str=="Jun") str="06";
    else if(str=="Jul") str="07";
    else if(str=="Aug") str="08";
    else if(str=="Sept") str="09";
    else if(str=="Oct") str="10";
    else if(str=="Nov") str="11";
    else if(str=="Dec") str="12";
}

//查询记录
void query(MYSQL *con,string str,string login_name,int conn)
{
    char flag=str[str.size()-1];
    cout<<"flag="<<flag<<endl;
    time_t now = time(0); // 把 now 转换为字符串形式 
    char* dt = ctime(&now); 
    string time(dt);
    string year=time.substr(20,4);
    // cout<<year<<endl;
    // cout<<strlen(dt)<<endl;
    string month=time.substr(4,3);

    // if(month=="Jul") cout<<"Yes"<<"!!!!!!!!!!!!!"<<endl;

    monthturn(month);
    // cout<<month<<endl;

    string day=time.substr(8,2);
    // cout<<month<<"!!!!!!!!"<<endl;
    // cout<<day<<endl;
    string sqlstr="select * from cost where name=\"";
    sqlstr+=login_name+"\" and time";
    if(flag=='1')
    {
        string time(year);
        time+=month+day;
        sqlstr+="="+time+";";
        cout<<sqlstr<<endl;
        mysql_query(con,sqlstr.c_str());
        // cout<<"zhe li ma ?"<<endl;
        // cout<<"00000000000000000"<<endl;
        auto result=mysql_store_result(con);
        // cout<<"1111111111111111111"<<endl;
        int col=mysql_num_fields(result);
        // cout<<"2222222222222222222"<<endl;
        int row=mysql_num_rows(result);
        // cout<<"333333333333333333"<<endl;
        // cout<<"row = "<<row;
        string res=inttos(row);
        // cout<<"    "<<res<<endl;
        send(conn,res.c_str(),res.size(),0);
        int sum=0;
        while(row--)
        {   
            // cout<<"begin!!!!!!!!!!"<<endl;
            auto info=mysql_fetch_row(result);
            // cout<<"end!!!!!!!!!!!!!!!"<<endl;
            string a;
            for(int i=1;i<col-1;++i)
            {
                a+=info[i];
                a+="  ";
            }
            // cout<<info[col-2]<<endl;
            sum+=atoi(info[col-3]);
            sleep(1);
            send(conn,a.c_str(),a.size(),0);
            sleep(1);
            cout<<a<<endl;
            // cout<<"why!!!!!!!!!!!!!"<<endl;
        }
        string ss=inttos(sum);
        cout<<ss<<endl;
        send(conn,ss.c_str(),ss.size(),0);
    }
    else if(flag=='2')
    {
        cout<<"施工中"<<endl;
    }
    else if(flag=='3')
    {
        cout<<"施工中"<<endl;
    }
}

void server::run()
{
    server_sockfd=socket(AF_INET,SOCK_STREAM,0);

    sockaddr_in server_addr;
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(server_port);
    server_addr.sin_addr.s_addr=inet_addr(server_ip.c_str());
    if(bind(server_sockfd,(sockaddr *)&server_addr,sizeof(server_addr))==-1)
    {
        perror("bind err");
        exit(1);
    }
    
    if(listen(server_sockfd,128)==-1)
    {
        perror("listen err");
        exit(1);
    }

    sockaddr_in client_addr;
    socklen_t length=sizeof(client_addr);
    while(1)
    {
        int conn=accept(server_sockfd,(sockaddr *)&client_addr,&length);
        if(conn==-1)
        {
            perror("accept  err");
            exit(1);
        }
        cout<<conn<<"客户端连接成功！"<<endl;
        sock_addr[conn]=true;
        thread t(server::RecvMsg,conn);
        t.detach();
    }
}

void server::RecvMsg(int conn)
{
    bool if_login=false;
    string login_name;
    char buffer[1000];
    while(1)
    {
        memset(buffer,0,sizeof(buffer));
        int len=recv(conn,buffer,sizeof(buffer),0);
        if(strcmp(buffer,"exit")==0||len<=0)
        {
            close(conn);
            sock_addr[conn]=false;
            break;
        }
        cout<<len<<endl;
        cout<<conn<<"发来的"<<buffer<<endl;
        string str(buffer);
        HandleRequest(conn,str,if_login,login_name);
    }
}

void server::HandleRequest(int conn,string str,bool &if_login,string &login_name)
{
    string name,pass,pass1;
    MYSQL *con=mysql_init(NULL); 
    mysql_real_connect(con,"127.0.0.1","root","12345678","project",0,NULL,CLIENT_MULTI_STATEMENTS);

    if(str.find("name:")!=str.npos)
    {
        int pos1=str.find("name:"),pos2=str.find("pass:");
        name=str.substr(pos1+5,pos2-5);
        pass=str.substr(pos2+5,str.length()-pos2-4);
        cout<<name<<endl<<pass<<endl;
        string sencens="insert into user value(\"";
        sencens+=name;
        sencens+="\",\"";
        sencens+=pass;
        sencens+="\");";
        cout<<sencens<<endl;
        mysql_query(con,sencens.c_str());
    }
    else if(str.find("login")!=str.npos)
    {
        int pos1=str.find("login"),pos2=str.find("pass:");
        name=str.substr(pos1+5,pos2-5);
        pass=str.substr(pos2+5,str.length()-pos2-4);
        string sqlstr="select * from user where name=\"";
        sqlstr+=name;
        sqlstr+="\";";
        cout<<sqlstr<<endl;
        int res = mysql_query(con,sqlstr.c_str());
        auto result=mysql_store_result(con);
        int col=mysql_num_fields(result);
        int row=mysql_num_rows(result);
        if(res==0&&row!=0)
        {
            auto ans = mysql_fetch_row(result);
            if(ans[1]==pass)
            {
                string answer="ok";
                if_login=true;
                login_name=name;
                cout<<login_name<<endl;
                send(conn,answer.c_str(),3,0);
            }
            else
            {
                string answer="wrong";
                send(conn,answer.c_str(),6,0);
            }
        }
        else
        {
            string answer="wrong";
            send(conn,answer.c_str(),6,0);
        }
    }
    //记账
    else if(if_login&&str.find("record")!=str.npos)
    { 
        // cout<<login_name<<endl<<endl;
        record(con,str,login_name);
        cout<<"记录成功"<<endl;
    }

    //查询记录
    else if(if_login&&str.find("query")!=str.npos)
    {
        cout<<"query!!!!!!!!!"<<endl;
        query(con,str,login_name,conn);
    }
}